#!/bin/bash

# ERP Mock Server 云端500错误诊断脚本
echo "🔍 诊断云端检验单查询500错误..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo "=================================================="
echo -e "${BLUE}ERP Mock Server 错误诊断工具${NC}"
echo "=================================================="

# 1. 检查服务状态
echo -e "${BLUE}📊 1. 检查服务状态...${NC}"
PYTHON_PID=$(ps aux | grep "[p]ython.*main.py" | awk '{print $2}')
if [ ! -z "$PYTHON_PID" ]; then
    echo -e "${GREEN}✅ 服务正在运行 (PID: $PYTHON_PID)${NC}"
else
    echo -e "${RED}❌ 服务未运行${NC}"
    exit 1
fi

# 2. 检查基础健康状态
echo -e "${BLUE}🔍 2. 检查基础健康状态...${NC}"
HEALTH_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3003/health)
if [ "$HEALTH_STATUS" == "200" ]; then
    echo -e "${GREEN}✅ 基础健康检查通过${NC}"
else
    echo -e "${RED}❌ 基础健康检查失败 (HTTP: $HEALTH_STATUS)${NC}"
fi

# 3. 检查检验单查询接口详细错误
echo -e "${BLUE}🧪 3. 测试检验单查询接口...${NC}"
echo "发送请求: POST /mock/yonbip/QMS_QIT/checkapply/list"

RESPONSE=$(curl -s -w "\nHTTP_CODE:%{http_code}" -X POST http://localhost:3003/mock/yonbip/QMS_QIT/checkapply/list \
  -H "Content-Type: application/json" \
  -d '{"pageIndex":1,"pageSize":5}')

HTTP_CODE=$(echo "$RESPONSE" | tail -n1 | sed 's/HTTP_CODE://')
RESPONSE_BODY=$(echo "$RESPONSE" | sed '$d')

echo -e "${BLUE}HTTP状态码: $HTTP_CODE${NC}"

if [ "$HTTP_CODE" == "200" ]; then
    echo -e "${GREEN}✅ 接口正常${NC}"
    echo "响应预览: $(echo "$RESPONSE_BODY" | head -c 200)..."
elif [ "$HTTP_CODE" == "500" ]; then
    echo -e "${RED}❌ 500错误确认${NC}"
    echo -e "${YELLOW}错误响应:${NC}"
    echo "$RESPONSE_BODY"
else
    echo -e "${YELLOW}⚠️ 其他HTTP错误: $HTTP_CODE${NC}"
    echo "$RESPONSE_BODY"
fi

# 4. 检查Python错误日志
echo -e "${BLUE}📝 4. 检查最近的错误日志...${NC}"
if [ -f "logs/app.log" ]; then
    echo -e "${BLUE}最近50行日志:${NC}"
    tail -50 logs/app.log | grep -E "(ERROR|Exception|Traceback|500)" --color=always || echo "未发现明显错误"
else
    echo -e "${YELLOW}⚠️ 日志文件不存在${NC}"
fi

# 5. 检查Python模块导入
echo -e "${BLUE}🐍 5. 检查Python环境和模块...${NC}"
python3 -c "
try:
    import sys
    sys.path.insert(0, '.')
    from app.api.inspection import inspection_bp
    from app.services.inspection_service import InspectionService
    print('✅ 检验单相关模块导入成功')
except ImportError as e:
    print(f'❌ 模块导入失败: {e}')
except Exception as e:
    print(f'❌ 其他错误: {e}')
"

# 6. 检查文件完整性
echo -e "${BLUE}📁 6. 检查关键文件是否存在...${NC}"
FILES=(
    "app/api/inspection.py"
    "app/services/inspection_service.py"
    "app/api/__init__.py"
    "main.py"
)

for file in "${FILES[@]}"; do
    if [ -f "$file" ]; then
        echo -e "${GREEN}✅ $file${NC}"
    else
        echo -e "${RED}❌ $file 缺失${NC}"
    fi
done

# 7. 检查蓝图注册
echo -e "${BLUE}🔧 7. 检查蓝图注册...${NC}"
if grep -q "inspection_bp" app/api/__init__.py; then
    echo -e "${GREEN}✅ 检验蓝图已注册${NC}"
else
    echo -e "${RED}❌ 检验蓝图未注册${NC}"
fi

# 8. 手动测试Python代码
echo -e "${BLUE}🧪 8. 手动测试检验服务...${NC}"
python3 -c "
try:
    import sys
    sys.path.insert(0, '.')
    from app.services.inspection_service import InspectionService

    # 测试服务方法
    result = InspectionService.query_inspection_list({'pageIndex': 1, 'pageSize': 5})
    print(f'✅ 服务测试成功，返回 {len(result.get(\"items\", []))} 条记录')
except Exception as e:
    print(f'❌ 服务测试失败: {e}')
    import traceback
    traceback.print_exc()
"

# 9. 生成修复建议
echo ""
echo "=================================================="
echo -e "${BLUE}📋 修复建议${NC}"
echo "=================================================="
echo -e "${YELLOW}1. 如果模块导入失败:${NC}"
echo "   cd /opt/erp-mock && git pull origin master"
echo ""
echo -e "${YELLOW}2. 如果Python路径问题:${NC}"
echo "   export PYTHONPATH=/opt/erp-mock:$PYTHONPATH"
echo ""
echo -e "${YELLOW}3. 如果服务启动问题:${NC}"
echo "   pkill -f python.*main.py"
echo "   cd /opt/erp-mock && python3 main.py"
echo ""
echo -e "${YELLOW}4. 查看实时错误日志:${NC}"
echo "   tail -f logs/app.log"
echo ""
echo -e "${YELLOW}5. 重新部署:${NC}"
echo "   bash scripts/hot_update.sh"

echo ""
echo "=================================================="
echo -e "${BLUE}诊断完成！${NC}"
echo "=================================================="